package com.marcowu.study.spb.tracing.resource;

import com.marcowu.study.spb.tracing.manager.SampleManager;
import com.marcowu.study.spb.tracing.zipkin.TracerBuiler;
import io.opentracing.Scope;
import io.opentracing.Span;
import io.opentracing.Tracer;
import io.opentracing.tag.Tags;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;

@Path("/tracing")
public class SampleResource {

  @Autowired
  private SampleManager sampleManager;

  private Tracer tracer = TracerBuiler.getZipkinTracer("SampleResource");

  @GET
  @Path("helloworld")
  public String helloworld() {
    Span span = tracer.buildSpan("helloworld").start();
    try (Scope scope = tracer.scopeManager().activate(span)) {
      sampleManager.sayHello();
      sampleManager.sayBye();
    } catch (Exception e) {
      Tags.ERROR.set(span, true);
    } finally {
      span.finish();
    }
    return "hello world";
  }

  @GET
  @Path("sayBye")
  public void sayBye(@Context HttpHeaders headers) {
    Span span = tracer.buildSpan("sayBye").start();
    try (Scope scope = tracer.scopeManager().activate(span)) {
      sampleManager.bye();
    } catch (Exception e) {
      Tags.ERROR.set(span, true);
    } finally {
      span.finish();
    }
  }

  @GET
  @Path("sayHello")
  public void sayHello(@Context HttpHeaders headers) {
    Span span = tracer.buildSpan("sayHello").start();
    try (Scope scope = tracer.scopeManager().activate(span)) {
      sampleManager.hello();
    } catch (Exception e) {
      Tags.ERROR.set(span, true);
    } finally {
      span.finish();
    }
  }

}
